package com.ljz.servlet;

import com.google.gson.Gson;
import com.ljz.dao.EmpDao;
import com.ljz.entity.Employ;
import com.ljz.utils.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/findNameByPage")
public class EmpByNameAndPageServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取页数
        Integer currentPage = Integer.parseInt(req.getParameter("currentPage"));
        Integer pageSize = Integer.parseInt(req.getParameter("pageSize"));
        String ename = req.getParameter("ename");
        //将页数和页的大小封装进一个map
        Map<String, Object> map = new HashMap<>();
        //计算出偏移量
        Integer currentPage1 = (currentPage-1)*pageSize;
        map.put("currentPage", currentPage1);
        map.put("pageSize", pageSize);
        map.put("ename", ename);
        //获取链接
        SqlSession sqlSession = SqlSessionFactoryUtil.getSqlSession();
        EmpDao empDao = sqlSession.getMapper(EmpDao.class);
        //调用dao接口去查数据
        List<Employ> empsByPage = empDao.findEmpByNameAndPage(map);
        //将数据封装进map集合
        Map<String, Object> map1 = new HashMap<>();
        map1.put("currentPage", currentPage);
        map1.put("pageSize", pageSize);
        //获取数据总条数
        int count = empDao.countEmpsByName(ename);
        //释放资源，防止连接会话占满
        sqlSession.close();
        //计算出一共的条数
        int total = count%pageSize==0?count/pageSize:count/pageSize+1;
        map1.put("total", total);
        map1.put("list", empsByPage);
        //json化
        Gson gson = new Gson();
        String json = gson.toJson(map1);
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(json);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
